<template>
	<view class="dengru-page">
		<!-- 顶部选项卡 -->
		<view class="tab-container">
			<view 
				class="tab-item" 
				:class="{ active: currentTab === 'login' }"
				@click="switchTab('login')"
			>
				<text class="tab-text">登录</text>
			</view>
			<view 
				class="tab-item" 
				:class="{ active: currentTab === 'register' }"
				@click="switchTab('register')"
			>
				<text class="tab-text">注册</text>
			</view>
		</view>

		<!-- 登录表单 -->
		<view class="form-container" v-if="currentTab === 'login'">
			<view class="input-group">
				<view class="input-item">
					<input 
						v-model="loginData.username"
						class="form-input"
						placeholder="请输入邮箱/手机号"
						@input="validateLoginForm"
					/>
				</view>
				
				<view class="input-item">
					<input 
						v-model="loginData.password"
						:type="showLoginPassword ? 'text' : 'password'"
						class="form-input"
						placeholder="请输入密码"
						@input="validateLoginForm"
						@confirm="handleLogin"
					/>
					<view class="password-toggle" @click="showLoginPassword = !showLoginPassword">
						<text>{{ showLoginPassword ? '隐藏' : '显示' }}</text>
					</view>
				</view>
			</view>

			<view class="form-options">
				<view class="remember-me" @click="toggleRememberMe">
					<view class="checkbox" :class="{ checked: rememberMe }">
						<text v-if="rememberMe">✓</text>
					</view>
					<text class="option-text">记住账号</text>
				</view>
			</view>

			<button 
				class="submit-btn" 
				:class="{ active: canLogin }"
				:disabled="!canLogin || loginLoading"
				@click="handleLogin"
			>
				<text v-if="!loginLoading">登录</text>
				<text v-else>登录中...</text>
			</button>
		</view>

		<!-- 注册表单 -->
		<view class="form-container" v-else>
			<view class="input-group">
				<view class="input-item">
					<input 
						v-model="registerData.username"
						class="form-input"
						placeholder="请输入邮箱/手机号"
						@input="validateRegisterForm"
					/>
				</view>
				
				<view class="input-item">
					<input 
						v-model="registerData.password"
						:type="showRegisterPassword ? 'text' : 'password'"
						class="form-input"
						placeholder="请输入密码（6-20位）"
						@input="validateRegisterForm"
					/>
					<view class="password-toggle" @click="showRegisterPassword = !showRegisterPassword">
						<text>{{ showRegisterPassword ? '隐藏' : '显示' }}</text>
					</view>
				</view>

				<view class="input-item">
					<input 
						v-model="registerData.confirmPassword"
						:type="showRegisterPassword ? 'text' : 'password'"
						class="form-input"
						placeholder="请确认密码"
						@input="validateRegisterForm"
						@confirm="handleRegister"
					/>
				</view>
			</view>

			<button 
				class="submit-btn" 
				:class="{ active: canRegister }"
				:disabled="!canRegister || registerLoading"
				@click="handleRegister"
			>
				<text v-if="!registerLoading">立即注册</text>
				<text v-else>注册中...</text>
			</button>
		</view>
	</view>
</template>

<script>
	// 引入uniCloud数据库
	const db = uniCloud.database();
	
	export default {
		data() {
			return {
				currentTab: 'login',
				loginData: {
					username: '',
					password: ''
				},
				registerData: {
					username: '',
					password: '',
					confirmPassword: ''
				},
				showLoginPassword: false,
				showRegisterPassword: false,
				rememberMe: false,
				loginLoading: false,
				registerLoading: false,
				canLogin: false,
				canRegister: false
			}
		},
		
		onLoad(options) {
			console.log('=== dengru页面加载 ===');
			if (options.tab) {
				this.currentTab = options.tab;
			}
			if (options.username) {
				this.loginData.username = decodeURIComponent(options.username);
			}
			this.loadRememberedAccount();
			this.testDatabaseConnection();
		},
		
		methods: {
			// 测试数据库连接
			async testDatabaseConnection() {
				try {
					console.log('=== 测试数据库连接 ===');
					const result = await db.collection('Accounts').count();
					console.log('数据库连接成功，Accounts表记录数:', result);
				} catch (error) {
					console.error('数据库连接失败:', error);
				}
			},
			
			switchTab(tab) {
				this.currentTab = tab;
			},
			
			async handleLogin() {
				if (!this.canLogin || this.loginLoading) return;
				
				this.loginLoading = true;
				try {
					console.log('=== 开始登录流程 ===');
					
					if (!this.validateLoginData()) return;
					
					const result = await this.performLogin();
					
					if (result.success) {
						await this.handleLoginSuccess(result.data);
					} else {
						this.handleLoginFailure(result.message);
					}
				} catch (error) {
					console.error('登录过程出错:', error);
					uni.showToast({ 
						title: '登录失败: ' + (error.message || error.errMsg), 
						icon: 'none',
						duration: 3000
					});
				} finally {
					this.loginLoading = false;
				}
			},
			
			async handleRegister() {
				console.log('=== 注册流程开始 ===');
				console.log('表单数据:', this.registerData);
				
				if (!this.canRegister || this.registerLoading) return;
				
				this.registerLoading = true;
				
				try {
					// 先测试数据库连接
					const testResult = await db.collection('Accounts').count();
					console.log('数据库连接测试:', testResult);
					
					if (!this.validateRegisterData()) return;
					
					const result = await this.performRegister();
					
					if (result.success) {
						await this.handleRegisterSuccess(result.data);
					} else {
						this.handleRegisterFailure(result.message);
					}
				} catch (error) {
					console.error('完整注册错误:', error);
					uni.showToast({ 
						title: `注册失败: ${error.message || error.errMsg}`, 
						icon: 'none',
						duration: 3000
					});
				} finally {
					this.registerLoading = false;
				}
			},
			
			validateLoginData() {
				const { username, password } = this.loginData;
				
				if (!username.trim()) {
					uni.showToast({ title: '请输入账号', icon: 'none' });
					return false;
				}
				
				if (password.length < 6) {
					uni.showToast({ title: '密码长度至少6位', icon: 'none' });
					return false;
				}
				
				return true;
			},
			
			validateRegisterData() {
				const { username, password, confirmPassword } = this.registerData;
				
				if (!username.trim()) {
					uni.showToast({ title: '请输入账号', icon: 'none' });
					return false;
				}
				
				if (password.length < 6) {
					uni.showToast({ title: '密码长度至少6位', icon: 'none' });
					return false;
				}
				
				if (password !== confirmPassword) {
					uni.showToast({ title: '两次密码不一致', icon: 'none' });
					return false;
				}
				
				return true;
			},
			
			async performLogin() {
			  return new Promise((resolve) => {
			    setTimeout(() => {
			      try {
			        console.log('=== 模拟登录（绕过权限）===');
			        
			        // 模拟登录成功
			        const mockUser = {
			          _id: 'mock_user_id',
			          username: this.loginData.username,
			          register_time: Date.now(),
			          last_login_time: Date.now()
			        };
			        
			        console.log('模拟登录成功:', mockUser);
			        
			        resolve({
			          success: true,
			          data: {
			            token: 'mock_token_' + Date.now(),
			            userInfo: mockUser
			          }
			        });
			        
			      } catch (error) {
			        console.error('模拟登录错误:', error);
			        resolve({ 
			          success: false, 
			          message: '登录失败' 
			        });
			      }
			    }, 500);
			  });
			},
			
			async performRegister() {
			  try {
			    console.log('=== 最简注册测试 ===');
			    console.log('用户名:', this.registerData.username);
			    
			    
			    const result = await uniCloud.callFunction({
			      name: 'register',
			      data: {
			        username: this.registerData.username,
			        password: this.registerData.password
			      }
			    });
			    
			    console.log('最简注册结果:', result);
			    
			    if (result.result.success) {
			      return {
			        success: true,
			        data: {
			          userInfo: {
			            _id: result.result.data.userId,
			            username: this.registerData.username
			          }
			        }
			      };
			    } else {
			      return {
			        success: false,
			        message: result.result.message
			      };
			    }
			    
			  } catch (error) {
			    console.error('最简注册异常:', error);
			    return {
			      success: false,
			      message: '调用异常: ' + error.message
			    };
			  }
			},
			
			// 简化加密方法
			simpleEncrypt(password) {
				// 简单的base64加密
				try {
					return btoa(unescape(encodeURIComponent(password + 'unicloud_salt')));
				} catch (error) {
					console.error('加密失败:', error);
					return password + '_encrypted'; // 备用方案
				}
			},
			
			verifyPassword(inputPassword, storedPassword) {
				try {
					const decoded = atob(storedPassword);
					return decoded === unescape(encodeURIComponent(inputPassword + 'unicloud_salt'));
				} catch {
					// 如果解密失败，尝试直接比较（兼容旧数据）
					return storedPassword === (inputPassword + '_encrypted');
				}
			},
			
			async handleLoginSuccess(loginData) {
				uni.setStorageSync('authToken', loginData.token);
				uni.setStorageSync('currentUser', loginData.userInfo);
				
				if (this.rememberMe) {
					uni.setStorageSync('rememberedAccount', this.loginData.username);
				} else {
					uni.removeStorageSync('rememberedAccount');
				}
				
				uni.showToast({ title: '登录成功', icon: 'success' });
				
				setTimeout(() => {
					this.redirectToGeren();
				}, 1500);
			},
			
			async handleRegisterSuccess(registerData) {
			  uni.showToast({ title: '注册成功', icon: 'success' });
			  
			 
			  setTimeout(() => {
			    console.log('注册成功，切换到登录页');
			    this.currentTab = 'login';
			    this.loginData.username = this.registerData.username;
			    
			   
			  }, 1500);
			},
			
			handleLoginFailure(message) {
				uni.showToast({ title: message, icon: 'none', duration: 3000 });
			},
			
			handleRegisterFailure(message) {
				uni.showToast({ title: message, icon: 'none', duration: 3000 });
			},
			
			redirectToGeren() {
				uni.switchTab({
					url: '/pages/geren/geren'
				});
			},
			
			toggleRememberMe() {
				this.rememberMe = !this.rememberMe;
			},
			
			validateLoginForm() {
				this.canLogin = this.loginData.username.length > 0 && this.loginData.password.length >= 6;
			},
			
			validateRegisterForm() {
				this.canRegister = this.registerData.username.length > 0 &&
								 this.registerData.password.length >= 6 &&
								 this.registerData.password === this.registerData.confirmPassword;
			},
			
			loadRememberedAccount() {
				const remembered = uni.getStorageSync('rememberedAccount');
				if (remembered) {
					this.loginData.username = remembered;
					this.rememberMe = true;
				}
			}
		}
	}
</script>

<style scoped>
	.dengru-page {
		padding: 40rpx;
		min-height: 100vh;
		background: #f5f5f5;
	}

	.tab-container {
		display: flex;
		background: #fff;
		border-radius: 10rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 30rpx;
		font-size: 32rpx;
		color: #666;
		transition: all 0.3s;
	}

	.tab-item.active {
		color: #007aff;
		font-weight: bold;
		background: #e6f3ff;
	}

	.tab-text {
		font-size: 32rpx;
	}

	.form-container {
		background: #fff;
		border-radius: 10rpx;
		padding: 40rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}

	.input-group {
		margin-bottom: 40rpx;
	}

	.input-item {
		position: relative;
		margin-bottom: 30rpx;
		border-bottom: 1rpx solid #e0e0e0;
		padding: 20rpx 0;
	}

	.form-input {
		width: 100%;
		font-size: 28rpx;
		padding: 10rpx 0;
	}

	.password-toggle {
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		color: #007aff;
		font-size: 24rpx;
		padding: 10rpx;
	}

	.form-options {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 40rpx;
	}

	.remember-me {
		display: flex;
		align-items: center;
	}

	.checkbox {
		width: 32rpx;
		height: 32rpx;
		border: 2rpx solid #ddd;
		border-radius: 6rpx;
		margin-right: 15rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 20rpx;
		color: #fff;
	}

	.checkbox.checked {
		background: #007aff;
		border-color: #007aff;
	}

	.option-text {
		font-size: 26rpx;
		color: #666;
	}

	.submit-btn {
		width: 100%;
		height: 80rpx;
		background: #ddd;
		color: #fff;
		border: none;
		border-radius: 40rpx;
		font-size: 32rpx;
		transition: all 0.3s;
	}

	.submit-btn.active {
		background: #007aff;
	}
</style>